import { StyleSheet, View, ActivityIndicator, ImageBackground } from 'react-native';
import React, { useEffect } from 'react';
import { useNavigation } from '@react-navigation/native';
import { userStore, observer, Storage, RecordKeys, webSocketStore } from '~/store';
import { useDeviceType, useBindDeviceList, useSocketUrl } from '~/common';

export default observer(() => {
    const navigation = useNavigation<any>();
    useDeviceType(); // 获取设备类型
    useBindDeviceList(); // 获取用户已经绑定的设备
    const socketURl = useSocketUrl() || 'wss://mqtt.shbjy.cn:443/mqtt';
    webSocketStore.initializeWebSocket(socketURl);
    const checkLogin = async () => {
        try {
            const profile = await Storage.getItem(RecordKeys.me);
            const token = profile?.token;
            if (!token) throw new Error('No token');
            let role = (await Storage.getItem(RecordKeys.roles)) || 'Main';
            userStore.signIn(profile);
            userStore.selectRole(role);
            switch (role) {
                case 'Acupoints':
                    navigation.navigate('AcupointsScreen');
                    break;
                case 'Doctor':
                    navigation.navigate('DoctorScreen');
                    break;
                case 'Main':
                    navigation.navigate('Main');
                    break;
                default:
                    navigation.navigate('Main');
                    break;
            }
        } catch (error) {
            userStore.selectRole('Main');
            navigation.navigate('Introduction');
        }
    };
    useEffect(() => {
        checkLogin();
    }, []);
    return (
        <View style={styles.container}>
            <ImageBackground style={styles.bg} source={require('~/assets/login/bg4.png')}>
                <ActivityIndicator size="large" color="#25C8C8" />
            </ImageBackground>
        </View>
    );
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    bg: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
});
